package com.example.test_15.controller;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.test_15.model.Captcha;
import com.example.test_15.model.Session;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class CaptchaController {
    @Autowired
    private Captcha captcha;
    private static final long settime =60*60;
    @RequestMapping("/captcha")
    public void getcaptcha(HttpServletResponse response, HttpSession httpSession) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight());
        response.setContentType("image/jpeg");
        httpSession.setAttribute(captcha.getSession().getCaptchaCode(),lineCaptcha.getCode());
        httpSession.setAttribute(captcha.getSession().getTime(),System.currentTimeMillis());
        System.out.println(lineCaptcha.getCode());

        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    @RequestMapping("code")
    public boolean getcode(String password,HttpSession httpSession){
        if(StringUtil.isNullOrEmpty(password)){
            return false;
        }
        long time=(long) httpSession.getAttribute(captcha.getSession().getTime());
        if(!httpSession.getAttribute(captcha.getSession().getCaptchaCode()).equals(password)&&System.currentTimeMillis()-time>settime){
            return false;
        }
        return true;
    }
}
